package com.mo.controller;


import com.mo.feign.ProvideFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ServiceController {
    @Autowired
    private RestTemplate restTemplate;
    //获取元数据信息
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ProvideFeignClient provideFeignClient;


    @RequestMapping("/get")
    public Map get() {
        Map<Integer, String> map = new HashMap<>();
        map = restTemplate.getForObject("http://localhost:9000/pro", Map.class);
        return map;
    }

    @RequestMapping("/get/{id}")
    public Map get(Integer id) {
        Map<String, String> map;
        List<ServiceInstance> list = discoveryClient.getInstances("provide");
        /*ServiceInstance instance = list.get(0);
        System.out.println(instance);*/
        //map = restTemplate.getForObject("http://" + instance.getHost() + ":" + instance.getPort()
        //        + "/pro",Map.class);
        //
        //调用的远程地址，不直接写主机地址，而是写注册表中注册的服务id
        map = restTemplate.getForObject("http://provide/pro", Map.class);
        return map;
    }

    /**
     * feign组件
     * 1，依赖
     * 2，开启注解
     * 3，设计获取调用的方法接口
     * 4，调用接口，实现远程调用
     *
     * @return
     */
    @RequestMapping("/feign")
    public Map getFeign() throws InterruptedException {
        Map<String, String> map;
        //Thread.sleep(2000);
        map = provideFeignClient.getProvide();
        return map;
    }


}
